package br.com.main.client.system.botoes;

import java.util.Date;
import java.util.List;

import br.com.main.client.ComunServico;
import br.com.main.client.ComunServicoAsync;
import br.com.main.client.system.botoes.FinanceiroView.Financas;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.datepicker.client.DateBox;

public class FinanceiroPresenter {
	
	Display display;

	interface Display {
		
		Button getBtCadastrar();

		List<Financas> getList();

		void atualizaTabela();

		void enableOrDesenable(boolean tipo);

		void clean();

		Label getLbNovaDespesa();

		TextBox getTbValor();

		TextBox getTbDescricao();

		Button getBtCancel();

		RadioButton getRadioSim();

		RadioButton getRadioNao();

		DateBox getDateBox();

		String[] getDados();
	}

	public FinanceiroPresenter(Display display) {
		this.display = display;
		bind();
		carregarTabela();
		display.enableOrDesenable(false);
	}

	
	private void carregarTabela() {
		getServico().carregarDespesas(new AsyncCallback<List<String[]>>() {
			
			@SuppressWarnings("deprecation")
			@Override
			public void onSuccess(List<String[]> arg0) {
				DateTimeFormat format = DateTimeFormat.getFormat("d/MM/y");
				
				display.getList().clear();
				
				for (String[] strings : arg0) {
					
					String data = format.format(new Date(strings[2]));
					
					display.getList().add(new Financas(strings[0], strings[1], data));
				}
				display.atualizaTabela();
				
			}
			
			@Override
			public void onFailure(Throwable arg0) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	private void bind() {
		
		display.getBtCadastrar().addClickHandler(new ClickHandler() {

			@Override
			public void onClick(ClickEvent event) {
			getServico().cadastroDespesa(display.getDados()[0], display.getDados()[1], display.getDados()[2],display.getDados()[3], new AsyncCallback<String>() {
				
				@Override
				public void onSuccess(String arg0) {
					
					carregarTabela();
					display.enableOrDesenable(false);
					display.clean();
				}
				
				@Override
				public void onFailure(Throwable arg0) {
					// TODO Auto-generated method stub
					
				}
			});
				
			}
		});
		
		display.getLbNovaDespesa().addClickHandler(new ClickHandler() {
			
			@Override
			public void onClick(ClickEvent arg0) {
				
				display.enableOrDesenable(true);
			}
		});

	}
	private ComunServicoAsync getServico() {
		return GWT.create(ComunServico.class);
	}
}
